package hng.service.impl;

import hng.model.ProductCategoryDO;
import hng.mapper.ProductCategoryMapper;
import hng.service.ProductCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import hng.vo.admin.ProductCategoryVO;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品分类表 服务实现类
 * </p>
 *
 * @author 告白
 * @since 2024-06-27
 */
@Service
public class ProductCategoryServiceImpl extends ServiceImpl<ProductCategoryMapper, ProductCategoryDO> implements ProductCategoryService {

    @Autowired(required = false)
    private ProductCategoryMapper productCategoryMapper;

    @Override
    public List<ProductCategoryVO> getAllCategories() {
        List<ProductCategoryVO> allCategories = productCategoryMapper.list();
        return buildCategoryTree(allCategories);
    }

    private List<ProductCategoryVO> buildCategoryTree(List<ProductCategoryVO> categories) {
        List<ProductCategoryVO> rootCategories = categories.stream()
                .filter(category -> category.getPid() == null || category.getPid() == 0)
                .collect(Collectors.toList());

        rootCategories.forEach(category -> {
            category.setChildren(getChildren(category, categories));
        });

        return rootCategories;
    }

    private List<ProductCategoryVO> getChildren(ProductCategoryVO root, List<ProductCategoryVO> allCategories) {
        return allCategories.stream()
                .filter(category -> Objects.equals(category.getPid(), root.getId()))
                .peek(category -> category.setChildren(getChildren(category, allCategories)))
                .collect(Collectors.toList());
    }
}
